package com.zz.common.handle;

import com.zz.common.config.Config;
import com.zz.common.enums.MessageType;
import com.zz.common.protocol.TunnelProtocol;
import com.zz.common.tunnel.TunnelCache;
import com.zz.common.utils.SnowflakeUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测
 *
 * @author zz
 */
@Slf4j
public class IdleCheckHandler extends IdleStateHandler {

    public static final int READ_IDLE_TIME = 60;

    public static final int WRITE_IDLE_TIME = 40;

    public IdleCheckHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext context, IdleStateEvent event) throws Exception {
        // 写空闲 在指定时间内没有写数据 触发
        if (IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT == event) {
            // 根据当前通信协议生成消息对象
            TunnelProtocol protocolMsg = Config.getInstance().getProtocol().newInstance();
            protocolMsg.setType(MessageType.TYPE_HEARTBEAT.getMark());
            protocolMsg.setSerialNumber(SnowflakeUtil.genSnowflakeId());
            // 缓存心跳消息
            TunnelCache.setHeartbeatCaches(context.channel(), protocolMsg.getSerialNumber());
            context.channel().writeAndFlush(protocolMsg);
            log.info("{}秒未传输数据,发送心跳包", TimeUnit.MILLISECONDS.toSeconds(super.getWriterIdleTimeInMillis()));
        } else if (IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT == event) {
            // 读空闲 在指定时间内没有读数据 关闭改通道
            TunnelCache.remoteHeartbeatCachesByChannel(context.channel());
//            context.channel().close();
//            log.info("{}秒未收到数据,断开连接", TimeUnit.MILLISECONDS.toSeconds(super.getReaderIdleTimeInMillis()));
        }
        super.channelIdle(context, event);
    }

}
